package com.liyou.full.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liyou.full.common.MyMetaObjectHandler;
import com.liyou.full.common.Result;
import com.liyou.full.pojo.Employee;
import com.liyou.full.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        log.info("员工登录:" + employee.toString());


        //1.根据员工提交的信息查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //2.查询该用户名是否（数据库用户名有唯一约束）
        if (null == emp){
            return Result.error("您输入的用户名有误");
        }

        //3.对员工提交的密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //4.比较密码
        if (!emp.getPassword().equals(password)){
            return Result.error("您输入的密码有误");
        }

        //5.查询用户状态，0为禁用，1为启用
        if (emp.getStatus() == 0){
            return Result.error("该用户已禁用");
        }

        //6.登陆成功，将员工id存入Session并返回结果

        //这里需要存入数据库查询出来的员工id，不然存入Session的是null
                                                //employee.getId()
        request.getSession().setAttribute("employee",emp.getId());
        return Result.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){

        log.info("员工退出");

        request.getSession().removeAttribute("employee");
        return Result.success("退出成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name){

        log.info("员工分页查询");

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();

        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);

        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //执行查询
        employeeService.page(pageInfo,queryWrapper);

        //返回结果
        return Result.success(pageInfo);

    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request,@RequestBody Employee employee){

        log.info("新增员工:" + employee.toString());

        //设置初始密码123456，进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //通过自动填充设置创建、修改时间以及创建、修改员工的员工id
        Long empId = (Long) request.getSession().getAttribute("employee");

        //存入员工信息到数据库
        employeeService.save(employee);

        return Result.success("添加成功");

    }


    /**
     * 修改员工状态信息
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody Employee employee){

        log.info("修改员工状态" + employee.toString());

        //获取当前员工id，自动填充更新修改时间和修改用户
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        employeeService.updateById(employee);
        return Result.success("修改成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id){

        log.info("查询员工:{id}：", id);

        Employee employee = employeeService.getById(id);

        if(employee != null){
            return Result.success(employee);
        }
        return Result.error("没有查询到对应员工信息");
    }

}
